﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DomainModel.Abstract;
using System.Data.Linq;
using System.Configuration;
using System.Diagnostics;
using System.Linq.Expressions;
using DomainModel.Entities;

namespace DomainModel.Concrete
{
    public class VOrderRepository:IVOrderRepository
    {
        private Table<vOrder> vordersTable;
        private DataContext dataContext;

        public VOrderRepository()
        {
            
            String cs = ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString();
            dataContext = new DataContext(cs);
            vordersTable = dataContext.GetTable<vOrder>();
        }

        public IQueryable<vOrder> Orders
        {
            get { return vordersTable; }
        }


        public IQueryable<vOrder> GetOrdersOrdered(vUser user)
        {
            if (user.IsClient)
            {
                return vordersTable.Where(a => a.UserID == user.UserID).OrderByDescending(usr => usr.OrderDate);
            }
            else
            {
                return vordersTable.Where(a => (a.StatusID>1)&&(a.ManagerID==user.UserID)).OrderByDescending(usr => usr.OrderDate);        
            }
        }


        public IQueryable<vOrder> GetOrdersOrdered(vUser user,DateTime DateFrom, DateTime DateTo, int UserID, int ManagerID)
        {
            if (user.IsClient)
            {
                UserID = user.UserID;
            }
            if (user.IsManager)
            {
                ManagerID = user.UserID;
            }
            Expression<Func<vOrder, bool>> u; 
            Expression<Func<vOrder, bool>> m;
            Expression<Func<vOrder, bool>> df; 
            Expression<Func<vOrder, bool>> dt;
            if (UserID > 0)
                u = x => x.UserID == UserID; 
            else u= x=> true;
            if (ManagerID > 0)
                m = x => x.ManagerID == ManagerID;
            else m = x => true;
            if (DateFrom.Year > 1)
                df = x => x.OrderDate >= DateFrom;
            else df = x => true;
            if (DateTo.Year > 1)
                dt = x => x.OrderDate < DateTo.AddDays(1);
            else dt = x => true;
            return vordersTable.Where(a => a.StatusID > 1).Where(u).Where(m).Where(df).Where(dt).OrderByDescending(usr => usr.OrderDate);
        }

        public vOrder GetOrder(Int32 id)
        {
            try
            {
                return vordersTable.First(d => d.OrderID == id);
            }
            catch (Exception exc)
            {
                return null;
            }
        }

        public void RefreshContext()
        {
            vordersTable.Context.Refresh(RefreshMode.OverwriteCurrentValues, vordersTable);
        }
    }
}
